from qturboframe.lib.utils.by import By
from qturboframe.lib.webdriver.exceptions import SeleniumError
from qturboframe.lib.report.log import logger
from qturboframe.public_ui.h_ui.base_table import BaseTable as HuiBaseTable

class BaseTable(HuiBaseTable):

    def get_title_list(self):
        if self._element.tag_name == 'table':
            title_list = list()
            th_list = self._element.find_elements_by_attribute(By.CSS_SELECTOR, 'thead>tr>th>div.h-table-cell', timeout=self.timeout)
            for th in th_list:
                th.focus()
                text = th.text
                title_list.append(text)
            return title_list
        else:
            raise SeleniumError('元素对象不为table对象，对象类型为： ' + self._element.tag_name)

    def auto_fill_row(self, target_row=0, input_data=None, td_index=0):

        def fill_value(tar_ele, index):
            td_list = tar_ele.find_elements_by_attribute('xpath', './/td//input')
            for i, input_ele in enumerate(td_list):
                value = input_data[i]
                input_ele.clear()
                input_ele.send_keys(value)
                logger.info(f'第{target_row}行，第{i+index}列，填充值是{value}')
            return True

        tr_list = self.get_tr_list()
        logger.debug(f'tr_list len: {len(tr_list)}, target_row: {target_row}')
        if target_row < len(tr_list):
            tar_row_ele = tr_list[target_row]
            fill_value(tar_row_ele, td_index)
        else:
            raise SeleniumError(f'target_row: {target_row} 不能大于等于表格行数 {len(tr_list)}')
